//
//  tree_DatasourceManager.m
//  Accordion
//
//  Created by Enriquez Gutierrez Guillermo Ignacio on 8/27/10.
//  Copyright (c) 2010 Nacho4D.
//  See the file license.txt for copying permission.
//

#import "tree_DatasourceManager.h"
#import "treeNode.h"
#import "SourceListItem.h"

#import "GBall.h"
#import "SourceListItem.h"
#import "PXTableObject.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBTableColumnHeader_key.h"

@interface tree_DatasourceManager ()

@property (nonatomic, retain, readwrite) NSMutableArray * mergedRootBranch;
@end


@implementation tree_DatasourceManager

@synthesize sortDescriptors = _sortDescriptors;
@synthesize mergedRootBranch = _mergedRootBranch;
@synthesize delegate;

#pragma mark -
#pragma mark 初始化與消滅

+ (NSMutableArray *) defaultSortDescriptors{
	
	NSSortDescriptor * sortDescType = [[NSSortDescriptor alloc] initWithKey:@"type" ascending:YES]; // Folders come first
	NSSortDescriptor * sortDescName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];  // Z ~ A
	NSSortDescriptor * sortDescCreationDate = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:YES];
	NSSortDescriptor * sortDescModificationDate = [[NSSortDescriptor alloc] initWithKey:@"modificationDate" ascending:YES];
	
	NSMutableArray *descs = [NSMutableArray arrayWithObjects:
							 sortDescName,                             
                             sortDescCreationDate,
							 sortDescType, 
                             sortDescModificationDate, nil];
	
	[sortDescType release];
	[sortDescName release];
	[sortDescCreationDate release];
	[sortDescModificationDate release];
	
	return descs;
}

-(void)set_branch{
    
    [_unmergedBranches removeAllObjects];
    [_mergedRootBranch removeAllObjects];
    
    NSMutableArray *filesAtRootLevel = [[NSMutableArray alloc] init];
    
    NSMutableArray *target;
    target=[[[datamodel_N4 Para_SLT_Paraent_Array] objectAtIndex:1] children];
    
    
    
    rootDirectory = [[treeNode alloc] initWithName:@"root_top" parentDirectory:[[[datamodel_N4 Para_SLT_Paraent_Array] objectAtIndex:1] paraent] selfDirectory:[[datamodel_N4 Para_SLT_Paraent_Array] objectAtIndex:1]   datamodel:datamodel_N4 parentkey:nil];
    
    [rootDirectory setLevel:-1];
    [rootDirectory setExpanded:YES];          
    
    for (SourceListItem *ti in target) {
        
        treeNode *aFile = [[treeNode alloc] initWithName:[ti title] parentDirectory:[ti paraent] selfDirectory:ti   datamodel:datamodel_N4 parentkey:rootDirectory];
        [ti setTreeNode_self:aFile];
        
        [aFile setLevel:0];
        [filesAtRootLevel addObject:aFile];
        [aFile release];
        
    }
    
    [_unmergedBranches setObject:filesAtRootLevel forKey:rootDirectory];
    [filesAtRootLevel release];
    
    
    
    
    [self _mergeBranches];
}

- (id) initWithRootPath:(NSString *)path sortDescriptors:(NSMutableArray *)sortDescs datamodel:(Data_Model *)dm{
	
	if (self = [super init]) {
		
		self.sortDescriptors = sortDescs;
		
        datamodel_N4=[dm retain];
        
        
                 
        
        _unmergedBranches = [[NSMutableDictionary alloc] init];
		_mergedRootBranch = [[NSMutableArray alloc] init];        
        [self set_branch];
        
        //根 key
      		
 	}
	return self;
}

- (void) dealloc{
	[_sortDescriptors release];
	[_mergedRootBranch release];
	[_unmergedBranches release];
    
    [datamodel_N4 release];
    
	delegate = nil;
	[super dealloc];
}

#pragma mark -
#pragma mark 列資料合併與排序


- (void) _sortBranches{
	for (NSMutableArray *branch in [_unmergedBranches allValues]){
		 [branch sortUsingDescriptors:self.sortDescriptors];
	}
}

- (void) _mergeBranches{
	NSLog(@"尚未開始合併");
    for (treeNode *keys in [_unmergedBranches allKeys] ) {
        NSLog(@"key name=%@",[keys name] );
    } 
    
    
	[self.mergedRootBranch setArray:[_unmergedBranches objectForKey:rootDirectory]];
	 
    NSMutableArray *branchKeys = [[_unmergedBranches allKeys] mutableCopy];
	
    NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES];
	[branchKeys sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
	
	NSInteger index = NSNotFound;
   
    
    for (treeNode *branchKey in branchKeys) {
		 
        if (branchKey == rootDirectory) continue;
		 
        
        NSMutableArray *unmergedBranch = [_unmergedBranches objectForKey:branchKey];
		
        index = [self.mergedRootBranch indexOfObject:branchKey];
		
        [self.mergedRootBranch replaceObjectsInRange:NSMakeRange(index+1, 0) withObjectsFromArray:unmergedBranch];
	}
    
    
	[sortDesc release];
	[branchKeys release];
	 
    
}
 

#pragma mark -
#pragma mark 資料夾展開與收斂
//打開下面資料夾
- (void) expandBranchAtIndex:(NSInteger)index{
    
	treeNode *directoryFile = [self.mergedRootBranch objectAtIndex:index];
    
    
       
    SourceListItem *si=[directoryFile self_path_SourceListItem];
    
    
    
    
	if (directoryFile.isDirectory) {
        
		//Make Branch:
        
		NSMutableArray *newBranch = [[NSMutableArray alloc] init];
        
        
        for (SourceListItem *ci in  [si children]  ) {
            //設定路徑
                     
            
            //從路徑取出 SourceListItem
            
            
            treeNode *aFile = [[treeNode alloc] initWithName:[ci title] parentDirectory:[ci paraent] selfDirectory:ci   datamodel:datamodel_N4 parentkey:directoryFile];
            [ci setTreeNode_self:aFile];            
            [aFile setLevel:directoryFile.level + 1];
			[newBranch addObject:aFile];
            [aFile release];            
            
        }
        
		//sort and add it unmerged branches
		// [newBranch sortUsingDescriptors:self.sortDescriptors];//排序使用
		
        [_unmergedBranches setObject:newBranch forKey:directoryFile];
        [newBranch release];
		
        
        
        
		//merge it:
		[_mergedRootBranch replaceObjectsInRange:NSMakeRange(index+1, 0) withObjectsFromArray:newBranch];
		[directoryFile setExpanded:YES];
		
		//call delegate
		if ([delegate respondsToSelector:@selector(fileAccordionDatasourceManager:didInsertRowsAtIndexPaths:)]) {
			NSMutableArray *paths = [NSMutableArray array]; 
			for (int i = 0; i < [newBranch count]; i++) {
				[paths addObject:[NSIndexPath indexPathForRow:(index + 1 + i) inSection:0]];
			}
			[delegate fileAccordionDatasourceManager:self didInsertRowsAtIndexPaths:paths];
		}
	}
    else {
        NSLog(@"顯示組合清單");
    }    
    
}
//收斂資料夾
- (void) collapseBranchAtIndex:(NSInteger)index;{
	
    treeNode *directoryFile = [self.mergedRootBranch objectAtIndex:index];
	
    
    if (directoryFile.isDirectory) {
		
		NSMutableArray *branchToCollapse = [_unmergedBranches objectForKey:directoryFile];
		NSLog(@"關閉數量=%i",[branchToCollapse count]);
        NSLog(@"%@ 關閉 新增資料夾後:%i", [directoryFile name]  ,  [[_unmergedBranches objectForKey:directoryFile] count]  ) ;        
		//recursively collapse expanded branches
		for (int i = 0; i < [branchToCollapse count]; i++) {
			
            treeNode *file = [branchToCollapse objectAtIndex:i];
			
            if (file.isDirectory && file.isExpanded) {
                
                [self collapseBranchAtIndex:index + i + 1]; //+1 is super important!!
                
            }
		}
		
		NSRange range = NSMakeRange(index+1, [branchToCollapse count]);
		[self.mergedRootBranch removeObjectsInRange:range];
		
        [_unmergedBranches removeObjectForKey:directoryFile];
		
        [directoryFile setExpanded:NO];
		
		//call delegate
		if ([delegate respondsToSelector:@selector(fileAccordionDatasourceManager:didRemoveRowsAtIndexPaths:)]) {
			
            NSMutableArray *paths = [NSMutableArray array]; 
			for (int i = 0; i < range.length; i++) {
				[paths addObject:[NSIndexPath indexPathForRow:(index + 1 + i) inSection:0]];
			}
            
            
            //收斂關鍵
            [delegate fileAccordionDatasourceManager:self didRemoveRowsAtIndexPaths:paths];
            
        }
		
	}
	
}
#pragma mark -
#pragma mark 群組與觀察名單 移動
- (void)treeNodemoveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{

    NSLog(@"sourceIndexPath=%i destinationIndexPath=%i",sourceIndexPath.row, destinationIndexPath.row );
    
    //取出原始位置的資料
    treeNode       *source_treeNode=[[self.mergedRootBranch objectAtIndex:sourceIndexPath.row] retain];
    SourceListItem *source_SourceListItem=[source_treeNode self_path_SourceListItem];
    SourceListItem *source_parent_SourceListItem=[source_SourceListItem paraent];
    treeNode       *source_parent_treeNode=[source_treeNode parentkey] ;        
    
    //取出目的地資料
    treeNode       *destination_treeNode;
    SourceListItem *destination_SourceListItem ;
    SourceListItem *destination_parent_SourceListItem ;
    treeNode       *destination_parent_treeNode ;    
   
     
    destination_treeNode=[self.mergedRootBranch objectAtIndex:destinationIndexPath.row ];
    destination_SourceListItem=[destination_treeNode self_path_SourceListItem];
    destination_parent_SourceListItem=[destination_SourceListItem paraent];
    destination_parent_treeNode= [destination_treeNode parentkey]; 
    
  
    NSLog(@"原始=%@ 原始父=%@ index=%i level=%i", [source_SourceListItem title]  ,[source_parent_SourceListItem title], [[source_parent_SourceListItem children] indexOfObject:  source_SourceListItem] ,[source_treeNode level]   );
    
    NSLog(@"目的=%@ 目的父=%@ index=%i level=%i", [destination_SourceListItem title]  ,[destination_parent_SourceListItem title] , [[destination_parent_SourceListItem children] indexOfObject:  destination_SourceListItem] ,[destination_treeNode level]  );          
   
    //0.節點相對應 父節點位置
    NSInteger source_index=[[source_parent_SourceListItem children] indexOfObject:  source_SourceListItem] ;
    NSInteger dest_index=[[destination_parent_SourceListItem children] indexOfObject:  destination_SourceListItem];        

    //呼叫合計所有次節點
    [datamodel_N4 node_sub_tree__to_array:source_SourceListItem];
    NSMutableArray *subarray=datamodel_N4.temp_all_sub_node;
    for (SourceListItem *sp in subarray ) {
        NSLog(@"ffff=%@",[sp title]);
    }
    if ([subarray indexOfObject:destination_SourceListItem]==NSNotFound) {
        NSLog(@"底下無相同");
    }
    else {
        NSLog(@"底下相同");
    }
    
    if (source_index != NSNotFound && dest_index !=NSNotFound) {
        if (source_parent_SourceListItem == destination_parent_SourceListItem) {
            //相同父節點內的移動
            
            
            //1.資料節點移動    
            [datamodel_N4 move_same_source:source_parent_SourceListItem source_index:source_index dese_index:dest_index];
            
            //2.取出的陣列 兩個父節點是相同
            
            NSMutableArray *brancha = [_unmergedBranches objectForKey:destination_parent_treeNode];
            
            
            int source_index_brancha=[brancha indexOfObject:  source_treeNode] ;
            int dest_index_brancha  =  [brancha indexOfObject:  destination_treeNode];        
            
            
            treeNode *temp=[[brancha objectAtIndex:source_index_brancha] retain];
            [brancha removeObjectAtIndex:source_index_brancha];
            
            [brancha insertObject:temp atIndex:dest_index_brancha];  
            
            [temp release];        
            
            
            
            //3.合併
            [self _mergeBranches];
            
            //4.重新顯示
            [delegate fileAccordionDatasourceManager_tree_reload];          
        }
        //[destination_treeNode level] <=[source_treeNode level]
        else if( [subarray indexOfObject:destination_SourceListItem]==NSNotFound) {
            NSLog(@"不同間的移動 且 移動目標的level 要小於或等於 來源level");
            
            int destination_level=[destination_treeNode level];
            
            
            
            
            //2.取出的陣列 兩個父節點是不相同
            
            NSMutableArray *branch_s = [_unmergedBranches objectForKey:source_parent_treeNode];
            NSMutableArray *branch_d = [_unmergedBranches objectForKey:destination_parent_treeNode];
            
            int source_index_brancha=[branch_s indexOfObject:  source_treeNode] ;
            int dest_index_brancha  =  [branch_d indexOfObject:  destination_treeNode];        
            
            //重新放在暫存 並且調正位置與父親
            treeNode *temp=[[branch_s objectAtIndex:source_index_brancha] retain];
            [temp setLevel:destination_level];
            [temp setParentkey:[destination_treeNode parentkey]];
                         
            //1.資料節點移動   
            
             [datamodel_N4 move_source:source_parent_SourceListItem dest:destination_parent_SourceListItem source_index:source_index dese_index:dest_index];        
            
             
            
            [branch_s removeObjectAtIndex:source_index_brancha];
            
            [branch_d insertObject:temp atIndex:dest_index_brancha];  
            
            [temp release];        
            
            
            
            //3.合併
            [self _mergeBranches];
            
            //4.重新顯示
            [delegate fileAccordionDatasourceManager_tree_reload];           
            // [delegate fileAccordionDatasourceManager_tree_reload];          
        }
        
        else {
            NSLog(@"不同間的移動 且 移動目標的level 大於 來源level＝可能會在自我以下階層內移動 所以不執行");        
            
            //呼叫表格更新畫面資料
            [delegate fileAccordionDatasourceManager_tree_reload];        
        } 
        
        
        
    }
    else {
        //呼叫表格更新畫面資料
        [delegate fileAccordionDatasourceManager_tree_reload];  
    }
          
    [source_treeNode release];  
     
    
}
#pragma mark -
#pragma mark 群組與觀察名單 更名
- (void) rename_AtIndex:(NSInteger)index newname:(NSString *)newname{
    
   
    treeNode *select_DirectoryorFile = [self.mergedRootBranch objectAtIndex:index];    
    
    NSLog(@"rename_AtIndex=%i name=%@",index,[select_DirectoryorFile name] );
    
   
    
    //2.取出資料庫上相對應的節點
    SourceListItem *select_node_SourceListItem=[select_DirectoryorFile self_path_SourceListItem];    
    
    
   
    //樹狀結點更新名稱
    [select_DirectoryorFile setName:newname];
   
    //資料庫結點更新名稱
    [datamodel_N4 Rename_SourceListItem:select_node_SourceListItem newName:newname];
    
     //呼叫表格更新畫面資料
    [delegate fileAccordionDatasourceManager_tree_reload];
}

#pragma mark -
#pragma mark 群組與觀察名單 刪除
- (void) deleteFileAtIndex:(NSInteger)index{
	NSLog(@"deleteFileAtIndex");
    
    treeNode *select_DirectoryorFile = [self.mergedRootBranch objectAtIndex:index];    
    if (select_DirectoryorFile.isDirectory && select_DirectoryorFile.isExpanded)
        [self collapseBranchAtIndex:index];
    
    
   
    //2.取出資料庫上相對應的節點
    SourceListItem *select_node_SourceListItem=[select_DirectoryorFile self_path_SourceListItem]; 
    
    
    //移除選定的節點
    [datamodel_N4 delete_singal_SourceListItem:select_node_SourceListItem];
    /*
    [[[select_node_SourceListItem paraent] children] removeObject:select_node_SourceListItem]; 
      [datamodel_N4 update_all_tree_folder_tableobject_refresh:1];     
      [datamodel_N4  update_all_tree_folder_to_sum];    
      [datamodel_N4 save_all_tree_data];  
    */
    

	 
	
	//delete file from merged branch
	[self.mergedRootBranch removeObjectAtIndex:index];
	
     
	
	//delete file from corresponding unmerged branch
	NSEnumerator *enumerator = [_unmergedBranches objectEnumerator];
	id branch;
	while ((branch = [enumerator nextObject])) {
		index = [branch indexOfObject:select_DirectoryorFile];
		if (index != NSNotFound) {
			[branch removeObjectAtIndex:index];
			break;
		}
	}
    
}

#pragma mark -
#pragma mark 群組與觀察名單 拷貝
- (void) copy_AtIndex:(NSInteger)index{
  
    NSLog(@"copy_AtIndex=%i",index);
    
    //1.依照選定列的位置 取出本身節點與父節點（5.會用到）
    treeNode *select_DirectoryorFile = [self.mergedRootBranch objectAtIndex:index];
     treeNode *parentkey              = [select_DirectoryorFile parentkey];
    //2.取出資料庫上相對應的節點
    SourceListItem *select_node_SourceListItem=[select_DirectoryorFile self_path_SourceListItem];
    
    //3.複製一個新資料夾
     SourceListItem *copyFolder;
     copyFolder= [datamodel_N4 copyFolder_on_select_tree_node: select_node_SourceListItem];
    [copyFolder setTitle:[NSString stringWithFormat:@"%@ Copy",[copyFolder title]]];
    
    //4.樹狀結構上 增加節點
    
    
    treeNode *newFile = [[treeNode alloc] initWithName:[copyFolder title] 
                                       parentDirectory:[copyFolder paraent] 
                                         selfDirectory:copyFolder
                                             datamodel:datamodel_N4 
                                             parentkey:parentkey];
    [copyFolder setTreeNode_self:newFile];
    
    [newFile   setLevel:[select_DirectoryorFile level]  ];
    
    
    //5.取出同一層的陣列
    NSMutableArray *branch = [_unmergedBranches objectForKey:parentkey];
    [branch addObject:newFile];
    [newFile release];
       
    
    //6.合併
    [self _mergeBranches];
    
    //7.樹狀表格上顯示
    NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:[self.mergedRootBranch indexOfObject:newFile] inSection:0];
    [delegate fileAccordionDatasourceManager:self didInsertRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];    
    

}

#pragma mark -
#pragma mark 群組與觀察名單 新增

//在選定的列上 同一階層上新增一個資料夾
- (void) createDirectoryAtIndex_level_same:(NSInteger)index withName:(NSString *)fileName{
	
   
    
    //1.依照選定列的位置 取出本身節點與父節點（5.會用到）
    treeNode *select_DirectoryorFile = [self.mergedRootBranch objectAtIndex:index];
    treeNode *parentkey              = [select_DirectoryorFile parentkey];
   
    
    
    NSLog(@"createDirectoryAtIndex_level_same=%@",[parentkey name] );  
    
    if (YES) {
        //parentkey!=rootDirectory        
        
        //2.取出資料庫上相對應的節點
        SourceListItem *select_node_SourceListItem=[select_DirectoryorFile self_path_SourceListItem];
        
        //3.資料庫結構新增一個資料夾
        SourceListItem *addFolder;
        addFolder= [datamodel_N4 addFolder_on_select_tree_node:select_node_SourceListItem];
        
        
        //4.樹狀結構上 增加節點
        
        
        treeNode *newFile = [[treeNode alloc] initWithName:[addFolder title] 
                                           parentDirectory:[addFolder paraent] 
                                             selfDirectory:addFolder
                                                 datamodel:datamodel_N4 
                                                 parentkey:parentkey];
        [addFolder setTreeNode_self:newFile];
        
        [newFile   setLevel:[select_DirectoryorFile level]  ];
        
        
        //5.取出同一層的陣列
        NSMutableArray *branch = [_unmergedBranches objectForKey:parentkey];
        [branch addObject:newFile];
        [newFile release];
        
        NSLog(@"branch=%i",[branch count] );
        for (treeNode *dd in branch  ) {
            NSLog(@"ddd=%@",dd.name);
        }
        
        
        //6.合併
        [self _mergeBranches];
        
        //7.樹狀表格上顯示
        NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:[self.mergedRootBranch indexOfObject:newFile] inSection:0];
        [delegate fileAccordionDatasourceManager:self didInsertRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];
        
        
        
    }
    else {
        NSLog(@"限制 頂層不可以加入自選群組");
        NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:index inSection:0];
        
        [delegate fileAccordionDatasourceManager:self didSelecrRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];       
    }
       
}

//在選定的列上 下一階層上新增一個資料夾
- (void) createDirectoryAtIndex_level_sub:(NSInteger)index withName:(NSString *)fileName{
	
    NSLog(@"createDirectoryAtIndex_level_sub" );
    
    //1.依照選定列的位置 取出本身節點與父節點（5.會用到）
    treeNode *select_DirectoryorFile = [self.mergedRootBranch objectAtIndex:index];
    //treeNode *parentkey              = [select_DirectoryorFile parentkey];
    
   
   
    
    //2.取出資料庫上相對應的節點
    SourceListItem *select_node_SourceListItem= [select_DirectoryorFile self_path_SourceListItem];
    
    //3.資料庫結構新增一個資料夾 下一個階層
    //SourceListItem *addFolder;
    [datamodel_N4 addFolder_on_select_tree_node_sub:select_node_SourceListItem];
    
    
	//7.樹狀表格上顯示
    
    if (select_DirectoryorFile.expanded==NO) {
        //如果本階層沒有展開 就本身點選來展開
        
        NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:index inSection:0];
        
        [delegate fileAccordionDatasourceManager:self didSelecrRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];
        
        
    }
    else {
        
        //本身已經展開 透過連續點選兩次來顯示
        NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:index inSection:0];
        
        [delegate fileAccordionDatasourceManager:self didSelecrRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];        
        [delegate fileAccordionDatasourceManager:self didSelecrRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]]; 
        
        
        
        
    }
    
    
}

//在選定的列上 同一階層上新增一個觀察名單
- (void) createWatchlistAtIndex_level_same:(NSInteger)index withName:(NSString *)fileName{
	NSLog(@"createWatchlistAtIndex_level_same");
    //1.依照選定列的位置 取出本身節點與父節點（5.會用到）
    treeNode *select_DirectoryorFile = [self.mergedRootBranch objectAtIndex:index];
    treeNode *parentkey              = [select_DirectoryorFile parentkey];
    
    
    if (YES) {
        //parentkey!=rootDirectory 
        //addwatchlist_on_select_tree_node    
        
        
        
        
        //2.取出資料庫上相對應的節點
        SourceListItem *select_node_SourceListItem=[select_DirectoryorFile self_path_SourceListItem];
        
        //3.資料庫結構新增一個資料夾 與 createDirectoryAtIndex_level_same 唯一的差別地方(addwatchlist_on_select_tree_node)
        SourceListItem *addFolder;
        addFolder= [datamodel_N4 addwatchlist_on_select_tree_node:select_node_SourceListItem];
        
        
        //4.樹狀結構上 增加節點
        
        
        treeNode *newFile = [[treeNode alloc] initWithName:[addFolder title] 
                                           parentDirectory:[addFolder paraent] 
                                             selfDirectory:addFolder
                                                 datamodel:datamodel_N4 
                                                 parentkey:parentkey];
        [addFolder setTreeNode_self:newFile];	
        [newFile setLevel:[select_DirectoryorFile level]  ];
        
        
        //5.取出同一層的陣列
        NSMutableArray *branch = [_unmergedBranches objectForKey:parentkey];
        [branch addObject:newFile];
        [newFile release];
        
        //6.合併
        [self _mergeBranches];
        
        //7.樹狀表格上顯示
        NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:[self.mergedRootBranch indexOfObject:newFile] inSection:0];
        [delegate fileAccordionDatasourceManager:self didInsertRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];
    }    
    else {
             NSLog(@"限制 頂層不可以加入自選名單");        
        
        NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:index inSection:0];
        
        [delegate fileAccordionDatasourceManager:self didSelecrRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];           
        
    }
   
	
    
}

//在選定的列上 下一階層上新增一個觀察名單
- (void) createWatchlistAtIndex_level_sub:(NSInteger)index withName:(NSString *)fileName{
    NSLog(@"createDirectoryAtIndex_level_sub" );
    
    //1.依照選定列的位置 取出本身節點與父節點（5.會用到）
    treeNode *select_DirectoryorFile = [self.mergedRootBranch objectAtIndex:index];
    //treeNode *parentkey              = [select_DirectoryorFile parentkey];
    
        
    //2.取出資料庫上相對應的節點
    SourceListItem *select_node_SourceListItem=[select_DirectoryorFile self_path_SourceListItem];
    
    //3.資料庫結構新增一個資料夾 下一個階層
    
    [datamodel_N4 addwatchlist_on_select_tree_node_sub:select_node_SourceListItem];
    
    
	
	//7.樹狀表格上顯示
    
    if (select_DirectoryorFile.expanded==NO) {
        //如果本階層沒有展開 就本身點選來展開
        NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:index inSection:0];
        
        [delegate fileAccordionDatasourceManager:self didSelecrRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];
    }
    else {
        //本身已經展開 透過連續點選兩次來顯示
        NSIndexPath *insertedIndex = [NSIndexPath indexPathForRow:index inSection:0];
        
        [delegate fileAccordionDatasourceManager:self didSelecrRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]];        
        [delegate fileAccordionDatasourceManager:self didSelecrRowsAtIndexPaths:[NSArray arrayWithObject:insertedIndex]]; 
    }
    
    
}


 
- (void) reloadAllBranches{
	//TODO:
}

  
 

- (treeNode *)_directoryToInsertFileAtIndex:(NSInteger)index{
	if (index < 0) return rootDirectory;
	
	treeNode *referenceFile = [self.mergedRootBranch objectAtIndex:index];
	treeNode *containerDirectory = nil;
	
	if (referenceFile.isDirectory){ //if is a directory create the file in it
		if (!referenceFile.isExpanded) [self expandBranchAtIndex:index];
		containerDirectory = referenceFile;
		
	} else if (referenceFile.level == 0) { //if is a file (not directory) in the first level, create in rootDirectory
		containerDirectory = rootDirectory;
		
	}else { //otherwise look for the correct folder to create in
		
		for (int i = index; i > 0 ; --i) {
			treeNode *file = [self.mergedRootBranch objectAtIndex:i];
			if (file.level < referenceFile.level) {
				containerDirectory = file;
				break;
			}
		}
	}
	
	return containerDirectory;
}

@end
